package com.zy.design.demo.behavioral;

import java.util.ArrayList;
import java.util.List;

/**
 * 迭代器模式
 * 特点：提供一种方法顺序访问聚合对象中的元素，而不暴露其内部结构。
 */
// 迭代器接口
interface Iterator1 {
    boolean hasNext();  // 是否有下一个元素
    Object next();      // 获取下一个元素
}

// 集合接口
interface Aggregate {
    Iterator1 createIterator();  // 创建迭代器
}

// 具体迭代器
class BookIterator implements Iterator1 {
    private BookCollection collection;
    private int index;

    public BookIterator(BookCollection collection) {
        this.collection = collection;
        this.index = 0;
    }

    public boolean hasNext() {
        return index < collection.size();
    }

    public Object next() {
        return collection.getBook(index++);
    }
}

// 具体集合
class BookCollection implements Aggregate {
    private List<String> books;

    public BookCollection() {
        this.books = new ArrayList<String>();
    }

    // 添加书籍
    public void addBook(String book) {
        books.add(book);
    }

    // 获取书籍
    public String getBook(int index) {
        return books.get(index);
    }

    // 获取集合的大小
    public int size() {
        return books.size();
    }
    public Iterator1 createIterator() {
        return new BookIterator(this);
    }
}

// 客户端代码
class Client0 {
    public static void main(String[] args) {
        BookCollection bookCollection = new BookCollection();
        bookCollection.addBook("Java Design Patterns");
        bookCollection.addBook("Effective Java");
        bookCollection.addBook("Spring in Action");

        Iterator1 iterator = bookCollection.createIterator();

        while (iterator.hasNext()) {
            String book = (String) iterator.next();
            System.out.println("Book: " + book);
        }
    }
}
